//
//  KZMenuView.m
//  KZTools_ObjectC
//
//  Created by 朱凯 on 2018/11/27.
//  Copyright © 2018年 zhukai. All rights reserved.
//

#import "KZMenuView.h"

@implementation KZMenuView
{
    UITableView *_table;
}

#pragma mark - 初始化
- (instancetype)init {
    
    if (self = [super init]) {
        
        _itemHeight = 40;
        _itemWidth = 100;
        _separatorColor = UIColor.lightGrayColor;
        _arrowDirection = KZMenuViewArrowDirectionDefault;
        _arrowSize = CGSizeMake(10, 6);
        _arrowPosition = 0.5;
        _corner = 2;
        _shadowAlpha = 0.3;
        _menuBackgroundColor = UIColor.whiteColor;
    }
    return self;
}

#pragma mark - 视图
- (void)showAtPoint:(CGPoint)point inView:(UIView *)view {
    
    if (_menuItems.count == 0) {
        return;
    }
    
    _table = [[UITableView alloc] init];
    _table.bounces = false;
    _table.backgroundColor = _menuBackgroundColor;
    _table.separatorColor = _separatorColor;
    _table.delegate = self;
    _table.dataSource = self;
    [self addSubview:_table];
    
    // 箭头的朝向
    if (_arrowDirection == KZMenuViewArrowDirectionDefault) {
        // 箭头位于上半区，则默认值转为up
        if (point.y < UIScreen.mainScreen.bounds.size.height / 2) {
            _arrowDirection = KZMenuViewArrowDirectionUp;
        } else {
            _arrowDirection = KZMenuViewArrowDirectionDown;
        }
    }
    
    // 确定箭头的位置，即锚点x的值
    CGFloat arrowMaxPosition = (_itemWidth - _corner - _arrowSize.width / 2) / _itemWidth;
    CGFloat arrowMinPosition = (_corner + _arrowSize.width / 2) / _itemWidth;
    _arrowPosition = MIN(MAX(arrowMinPosition, _arrowPosition), arrowMaxPosition);
    
    // 确定table的frmae
    CGFloat w = _itemWidth;
    CGFloat h = _itemHeight * _menuItems.count + _arrowSize.height;
    CGFloat x = point.x - _arrowPosition * w;
    CGFloat y = _arrowDirection == KZMenuViewArrowDirectionUp ? point.y : (point.y - h);
    _table.frame = CGRectMake(x, y, w, h);
    
    // 确定箭头的位置
    CGPoint arrowPoint = CGPointMake(_arrowPosition * w, _arrowDirection == KZMenuViewArrowDirectionUp ? 0 : h);

    // 确定遮罩视图的边框
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.fillColor = UIColor.greenColor.CGColor;
    UIBezierPath *path = [self borderPath:arrowPoint];
    layer.path = path.CGPath;
    _table.layer.mask = layer;
    
    // 设置table的锚点，以实现基于箭头的缩放动画
    CGRect frame = _table.frame;
    _table.layer.anchorPoint = CGPointMake(_arrowPosition, _arrowDirection == KZMenuViewArrowDirectionUp ? 0 : 1);
    _table.frame = frame;
    
    // 添加本视图
    [view addSubview:self];
    self.frame = view.bounds;
    [self addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
    
    // 动画
    [self show];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _menuItems.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.backgroundColor = UIColor.clearColor;
    }
    
    KZMenuViewItem *item = _menuItems[indexPath.row];
    cell.textLabel.textColor = item.titleColor;
    cell.textLabel.font = item.titleFont;
    cell.textLabel.text = item.title;
    cell.imageView.image = item.image;
    
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return _itemHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return _arrowDirection == KZMenuViewArrowDirectionUp ? _arrowSize.height : 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return UIView.new;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return _arrowDirection == KZMenuViewArrowDirectionDown ? _arrowSize.height : 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return UIView.new;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:false];
    if (_itemClickBlock) {
        _itemClickBlock(indexPath.row);
    }
    [self hide];
}

#pragma mark - 事件
- (void)show {
    
    self.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0];
    
    _table.layer.transform = CATransform3DMakeScale(CGFLOAT_MIN, CGFLOAT_MIN, 1);
    
    [UIView animateWithDuration:0.4 delay:0 usingSpringWithDamping:1 initialSpringVelocity:0 options:0 animations:^{
        self.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:self.shadowAlpha];
        self->_table.layer.transform = CATransform3DIdentity;
    } completion:^(BOOL finished) {
        
    }];
}
- (void)hide {
    
    [UIView animateWithDuration:0.4 delay:0 usingSpringWithDamping:1 initialSpringVelocity:0 options:0 animations:^{
        self.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0];
        self->_table.layer.transform = CATransform3DMakeScale(0.01, 0.01, 1);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}




#pragma mark - getter
- (UIBezierPath *)borderPath:(CGPoint)arrowPoint {
    
    // 箭头的点，基于窗口
    CGFloat arrowWidth = _arrowSize.width;
    CGFloat arrowHeight = _arrowSize.height;
    CGFloat corner = _corner;
    
    

    CGFloat width = _table.width;
    CGFloat height = _table.height;
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:arrowPoint];
    // 箭头朝上，顺时针添加路径
    if (_arrowDirection == KZMenuViewArrowDirectionUp) {
        [path addLineToPoint:CGPointMake(arrowPoint.x + arrowWidth / 2, arrowPoint.y + arrowHeight)];
        [path addLineToPoint:CGPointMake(width - corner, arrowPoint.y + arrowHeight)];
        [path addArcWithCenter:CGPointMake(width - corner, arrowPoint.y + arrowHeight + corner) radius:corner startAngle:-M_PI / 2 endAngle:0 clockwise:YES];
        [path addLineToPoint:CGPointMake(width, arrowPoint.y + arrowHeight + corner)];
        [path addLineToPoint:CGPointMake(width, height - corner)];
        [path addArcWithCenter:CGPointMake(width - corner, height - corner) radius:corner startAngle:0 endAngle:M_PI / 2 clockwise:YES];
        [path addLineToPoint:CGPointMake(width - corner, height)];
        [path addLineToPoint:CGPointMake(corner, height)];
        [path addArcWithCenter:CGPointMake(corner, height - corner) radius:corner startAngle:M_PI / 2 endAngle:M_PI clockwise:YES];
        [path addLineToPoint:CGPointMake(0, height - corner)];
        [path addLineToPoint:CGPointMake(0, arrowPoint.y + arrowHeight + corner)];
        [path addArcWithCenter:CGPointMake(corner, arrowPoint.y + arrowHeight + corner) radius:corner startAngle:M_PI endAngle:M_PI / 2 * 3 clockwise:YES];
        [path addLineToPoint:CGPointMake(corner, arrowPoint.y + arrowHeight)];
        [path addLineToPoint:CGPointMake(arrowPoint.x - arrowWidth / 2, arrowPoint.y + arrowHeight)];
        [path closePath];
    }
    // 箭头朝下，顺时针添加路径
    else {
        [path addLineToPoint:CGPointMake(arrowPoint.x - arrowWidth / 2, arrowPoint.y - arrowHeight)];
        [path addLineToPoint:CGPointMake(corner, arrowPoint.y - arrowHeight)];
        [path addArcWithCenter:CGPointMake(corner, arrowPoint.y - arrowHeight - corner) radius:corner startAngle:M_PI / 2 endAngle:M_PI clockwise:YES];
        [path addLineToPoint:CGPointMake(0, arrowPoint.y - arrowHeight - corner)];
        [path addLineToPoint:CGPointMake(0, corner)];
        [path addArcWithCenter:CGPointMake(corner, corner) radius:corner startAngle:M_PI endAngle:M_PI / 2 * 3 clockwise:YES];
        [path addLineToPoint:CGPointMake(corner, 0)];
        [path addLineToPoint:CGPointMake(width - corner, 0)];
        [path addArcWithCenter:CGPointMake(width - corner, corner) radius:corner startAngle:M_PI / 2 * 3 endAngle:M_PI * 2 clockwise:YES];
        [path addLineToPoint:CGPointMake(width, arrowHeight)];
        [path addLineToPoint:CGPointMake(width, arrowPoint.y - arrowHeight - corner)];
        [path addArcWithCenter:CGPointMake(width - corner, arrowPoint.y - arrowHeight - corner) radius:corner startAngle:0 endAngle:M_PI / 2 clockwise:YES];
        [path addLineToPoint:CGPointMake(width - corner, arrowPoint.y - arrowHeight)];
        [path addLineToPoint:CGPointMake(arrowPoint.x + arrowWidth / 2, arrowPoint.y - arrowHeight)];
        [path closePath];
    }
    
    return path;
}




@end



@implementation KZMenuViewItem

- (instancetype)init {
    if (self = [super init]) {
        _title = @"";
        _titleFont = [UIFont systemFontOfSize:15];
        _titleColor = UIColor.blackColor;
        _image = nil;
    }
    return self;
}
@end
